import React, { useState } from 'react';

import { Upload, message, Modal } from 'antd';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import { UploadOutlined } from '@ant-design/icons';

export default function TestPage() {
  const [imgSrc, setImgSrc] = useState('');
  const [fileList, setFileList] = useState([]);
  const props = {
    name: 'image',
    accept: '.png,.jpg',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      setFileList(info.fileList);
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
    onPreview(file) {
      setImgSrc(file.thumbUrl);
    },
    beforeUpload(file) {
      const imgs = ['image/jpg', 'image/png'];

      if (!imgs.includes(file.type)) {
        message.warning('不允许上传的文件类型');
        return Upload.LIST_IGNORE;
      }
    },
  };
  return (
    <div>
      <Upload {...props} listType="picture-card" fileList={fileList}>
        {fileList.length === 3 ? null : <UploadOutlined />}
      </Upload>
      <Modal
        title="预览图片"
        visible={!!imgSrc}
        footer={null}
        onCancel={() => setImgSrc('')}
      >
        <img width={480} style={{ objectFit: 'cover' }} src={imgSrc} alt="" />
      </Modal>
    </div>
  );
}
